package com.zkingsoft.wechat;

import static com.zkingsoft.common.constance.AppConstance.SAFEPATH;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.PropertiesUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.tools.WebUtil;
import com.matrix.core.web.BaseAction;
import com.zkingsoft.biz.bean.DataDictionary;
import com.zkingsoft.biz.dao.DataDictionaryDao;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.laqeelin.bean.BizHelp;
import com.zkingsoft.laqeelin.bean.BizHelpActivity;
import com.zkingsoft.laqeelin.bean.BizOrder;
import com.zkingsoft.laqeelin.bean.BizQrcode;
import com.zkingsoft.laqeelin.bean.BizShare;
import com.zkingsoft.laqeelin.bean.BizUser;
import com.zkingsoft.laqeelin.bean.DataDecipheringVo;
import com.zkingsoft.laqeelin.dao.BizHelpActivityDao;
import com.zkingsoft.laqeelin.dao.BizHelpDao;
import com.zkingsoft.laqeelin.dao.BizOrderDao;
import com.zkingsoft.laqeelin.dao.BizQrcodeDao;
import com.zkingsoft.laqeelin.dao.BizShareDao;
import com.zkingsoft.laqeelin.service.BizHelpActivityService;
import com.zkingsoft.laqeelin.service.BizHelpService;
import com.zkingsoft.laqeelin.service.BizShareService;
import com.zkingsoft.redis.RedisUserLoginUtils;
import com.zkingsoft.tools.AES;
import com.zkingsoft.tools.WxacodeUtil;


/**
 * @description (助力活动表)
 * @author 何明
 * @date 2018-09-01 10:35
 */
@Controller
@RequestMapping(value = "wxapi/helpActivity")
public class WxHelpActivityAction extends BaseAction{

	@Autowired
	private BizHelpActivityService bizHelpActivityService;
	@Autowired
	private BizShareService bizShareService;
	
	@Autowired
	private DataDictionaryDao dataDictionaryDao;
	@Autowired
	private BizHelpActivityDao helpActivityDao;
	@Autowired
	RedisUserLoginUtils redisUserLoginUtils;
	@Autowired
	private BizShareDao bizShareDao;
	@Autowired
	private BizHelpDao bizHelpDao;
	@Autowired
	private BizHelpService bizHelpService;
	@Autowired
	private BizOrderDao bizOrderDao;
	
	@Autowired
	private BizQrcodeDao bizQrcodeDao;
	
	//记录编辑前的值Before_Edit_Value
	public static final String BEV="BizHelpActivity_BEV";
	
	/**
	 * 查询活动详情
	 */   
   	@RequestMapping(value =  "/queryDetail/{actId}")
	public @ResponseBody AjaxResult queryDetail(@PathVariable("actId") String actId) {
		//BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		BizHelpActivity helpActivity=helpActivityDao.selectByActId(actId);
	 	return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(helpActivity));
	}
   	
   	/**
	 * 查询店铺首页
	 */   
   	@RequestMapping(value =  "/queryCompanyInfo")
	public @ResponseBody AjaxResult queryCompanyInfo() {
   		DataDictionary dataDictionary=new DataDictionary();
		dataDictionary.setTypeCode("company_info");
		List<DataDictionary> list=dataDictionaryDao.selectByModel(dataDictionary);
		dataDictionary=list.get(0);
		
		BizHelpActivity act=new BizHelpActivity();
		act.setHacStatus(AppConstance.ACT_STATUS_FB);
		List<BizHelpActivity> actList=helpActivityDao.selectByModel(act);
		dataDictionary.setActList(actList);
		return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(dataDictionary));
	}
 	
   	/**
	 * 分享成功
	 */   
   	@RequestMapping(value =  "/addShare/{actId}")
	public @ResponseBody AjaxResult addShare(@PathVariable("actId") String actId) {
   		BizHelpActivity helpActivity=helpActivityDao.selectByActId(actId);
   		if(helpActivity==null){
   			return new AjaxResult(AjaxResult.STATUS_FAIL,"失败");
   		}
   		BizShare bizShare=new BizShare();
   		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		bizShare.setProId(actId);
   		bizShare.setUserId(loginUser.getOpenId());
   		List<BizShare> list=bizShareDao.selectByModel(bizShare);
   		if(CollectionUtils.isEmpty(list)){
   			bizShare.setCreateBy(loginUser.getOpenId());
   			bizShare.setUpdateBy(loginUser.getOpenId());
   			bizShare.setShaStatus(AppConstance.SHARE_STATUS_YFX);
   			bizShare.setShaId(UUIDUtil.getRandomID());
   		   int i= bizShareDao.insert(bizShare);
	   		if(i>0){
	   		   return new AjaxResult(AjaxResult.STATUS_SUCCESS,"分享成功");
	   		}
   		}
   		return new AjaxResult(AjaxResult.STATUS_FAIL,"此活动已分享过");
	}
 	/**
	 * 助力 自己不能为自己助力
	 */   
   	@RequestMapping(value =  "/addHelp/{actId}/{openId}/{formId}")
	public @ResponseBody AjaxResult addHelp(@PathVariable("actId") String actId,@PathVariable("openId") String openId,@PathVariable("formId") String formId) {
   		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		if(loginUser.getOpenId().equals(openId)){
				return new AjaxResult(AjaxResult.STATUS_FAIL,"不能为自己助力!");
			}
   		BizShare bizShare=bizShareDao.selectShareInfo(openId,actId);
   		if(bizShare!=null ){
   			if(bizShare.getActivity()==null){
   				return new AjaxResult(AjaxResult.STATUS_FAIL,"此活动已结束!");
   			}
   			if(bizShare.getShaStatus()!=AppConstance.SHARE_STATUS_YFX ){
   				return new AjaxResult(AjaxResult.STATUS_FAIL,"此活动已完成!");
   			}
   			//查询是否已经助力
   			BizHelp help=new BizHelp();
   			help.setShareId(bizShare.getShaId());
   			help.setUserId(loginUser.getOpenId());
   			help.setNickName(loginUser.getNickName());
   			List<BizHelp> helpList=bizHelpDao.selectByModel(help);
   			if(CollectionUtils.isNotEmpty(helpList)){
   				return new AjaxResult(AjaxResult.STATUS_FAIL,"不能重复助力!");
   			}else{
   				help.setCreateBy(loginUser.getOpenId());
   	   			help.setUpdateBy(loginUser.getOpenId());
   	   			help.setHelpId(UUIDUtil.getRandomID());
   	   			int i= bizHelpService.addHelp(help, bizShare,formId);
   	   			if(i>0){
	   	   			BizOrder order=bizHelpService.receiveHelpPrize(bizShare.getShaId(), loginUser,formId);
	   	   			LogUtil.debug("订单信息:{}", order);
   	   				return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(order));
   	   			}
   			}
   			
   		}
   		return new AjaxResult(AjaxResult.STATUS_FAIL,"助力失败");
		
	}
	
	/**
	 * 查询分享的活动详情
	 */   
   	@RequestMapping(value =  "/queryShare/{actId}/{openId}")
	public @ResponseBody AjaxResult queryDetail(@PathVariable("actId") String actId,@PathVariable("openId") String openId) {
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		BizShare bizShare=bizShareDao.selectShareInfo(openId,actId);
   		if(bizShare==null){
   			return new AjaxResult(AjaxResult.STATUS_FAIL,"查询活动失败");
   		}
   		BizOrder order=new BizOrder();
   		order.setUserId(loginUser.getOpenId());
   		order.setShareId(bizShare.getShaId());
   		List<BizOrder> list=
   		bizOrderDao.selectByModel(order);
   		if(CollectionUtils.isNotEmpty(list)){
   			bizShare.setOrderId(list.get(0).getOrderId());
   		}
	 	return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(bizShare));
	}
   	
   	/**
	 * 领取分享礼品
	 */   
   	@RequestMapping(value =  "/receiveSharePrize")
	public @ResponseBody AjaxResult receiveSharePrize(@RequestBody BizOrder order) {
   		LogUtil.debug("领取信息:{}", order);
   		if(order==null || StringUtils.isBlank(order.getShareId())
   				|| StringUtils.isBlank(order.getUserPhone())){
	   		   return new AjaxResult(AjaxResult.STATUS_FAIL,"参数错误");
	   		}
   		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		
   		BizOrder bizOrder=bizHelpService.receiveSharePrize(loginUser, order);
	   		
	   	return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(bizOrder));
	   		
	}
   	
 	/**
	 * 领取助力礼品
	 */   
  /* 	@RequestMapping(value =  "/receiveHelpPrize/{shaId}")
	public @ResponseBody AjaxResult receiveHelpPrize(@PathVariable("shaId") String shareId) {
   		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		
   		int i=bizHelpService.receiveHelpPrize( shareId, loginUser);
	   		if(i>0){
	   		   return new AjaxResult(AjaxResult.STATUS_SUCCESS,"领取成功");
	   		}
   		
   		return new AjaxResult(AjaxResult.STATUS_FAIL,"领取失败");
	}*/
   	
	/**
	 * 查询我所有礼品
	 */   
   	@RequestMapping(value =  "/queryPrize")
	public @ResponseBody AjaxResult queryDetail() {
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		
		List<BizOrder> orderList=bizOrderDao.selectByOpenId(loginUser.getOpenId());
	 	return new AjaxResult(AjaxResult.STATUS_SUCCESS,orderList);
	}
	/**
	 * 查看订单
	 */   
  	@RequestMapping(value =  "/showOrder/{orderId}")
	public @ResponseBody AjaxResult receiveHelpPrize(@PathVariable("orderId") String orderId) {
   		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		BizOrder order =new BizOrder();
   		order.setUserId(loginUser.getOpenId());
   		order.setOrderId(orderId);
	   	return new AjaxResult(AjaxResult.STATUS_SUCCESS,bizOrderDao.selectByModel(order));
	   	
	}
  	
  	/**
	 * 手机号码解密
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年8月28日
	 * @param dataDecipheringVo
	 * @return
	 */
	@RequestMapping(value = "/deciphering")
	public @ResponseBody AjaxResult deciphering(@RequestBody DataDecipheringVo dataDecipheringVo) {
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		String session_key = loginUser.getSessionKey();
		LogUtil.debug(dataDecipheringVo.toString());
		String jsonResult = AES.wxDecrypt(dataDecipheringVo.getEncryptedData(), session_key, dataDecipheringVo.getIv());
		AjaxResult result = new AjaxResult();
		result.setStatus(AjaxResult.STATUS_SUCCESS);
		result.putInMap("decipher", jsonResult);
		return result;
	}
	
  	/**
	 * 查询前10位助力人
	 */   
   	@RequestMapping(value =  "/selectHelps")
	public @ResponseBody AjaxResult selectHelps() {
   		
   		List<BizHelp> helps=bizHelpDao.selectHelps();
	   		
	   	return new AjaxResult(AjaxResult.STATUS_SUCCESS,helps);
	   		
	}
	/**
	 * 生成二维码
	 */   
   	@RequestMapping(value =  "/getwxacode/{actId}")
	public @ResponseBody AjaxResult getwxacode(@PathVariable("actId") String actId) {
   		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		String url;
		try {
			BizShare bizShare=new BizShare();
			BizQrcode bizQrcode=new BizQrcode();
			bizQrcode.setActId(actId);
			bizQrcode.setUserId(loginUser.getOpenId());
			List<BizQrcode> list=
			bizQrcodeDao.selectByModel(bizQrcode);
			if(CollectionUtils.isEmpty(list)){
				//如果未查询到就先插入数据再更新数据
				bizQrcode.setCreateBy(loginUser.getOpenId());
				bizQrcode.setUpdateBy(loginUser.getOpenId());
				bizQrcodeDao.insert(bizQrcode);
				url = WxacodeUtil.getWxacode(bizQrcode.getCodeId()+"", "pages/active/active", actId+loginUser.getUserId());
				bizQrcode.setCodeUrl(url);
				BizHelpActivity helpActivity=helpActivityDao.selectByActId(actId);
				String posterImg=helpActivity.getHacPosterImg();
				// 图片保存目录路径
				String baseSavePath = PropertiesUtil.getString(AppConstance.FILES_TORAGE_PATH);
				// 图片保存目录URL
				String baseSaveUrl = PropertiesUtil.getString(AppConstance.NGINX_URL);
				posterImg=posterImg.replace(baseSaveUrl, baseSavePath);
				String smallUrl=url.replace(baseSaveUrl, baseSavePath);
				BufferedImage big = ImageIO.read(new File(posterImg));
		        BufferedImage small = ImageIO.read(new File(smallUrl));
		        Graphics2D g = big.createGraphics();
		        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));
		        g.drawImage(small, helpActivity.getBizCodePosition().getX(),
		        		helpActivity.getBizCodePosition().getY(), helpActivity.getBizCodePosition().getWidth(), 
		        		helpActivity.getBizCodePosition().getHeight(), null);
		        g.dispose();
		        String fileName=UUIDUtil.getRandomID()+".png";
		        	
		        ImageIO.write(big, "png", new File(baseSavePath+fileName));
		        bizQrcode.setCodeRemark(baseSaveUrl+fileName);
				bizQrcodeDao.updateByModel(bizQrcode);
		   		
		   		bizShare.setProId(actId);
		   		bizShare.setUserId(loginUser.getOpenId());
		   		List<BizShare> sharelist=bizShareDao.selectByModel(bizShare);
		   		if(CollectionUtils.isEmpty(sharelist)){
		   			bizShare.setCreateBy(loginUser.getOpenId());
		   			bizShare.setUpdateBy(loginUser.getOpenId());
		   			bizShare.setShaStatus(AppConstance.SHARE_STATUS_YFX);
		   			
		   			bizShare.setShaId(UUIDUtil.getRandomID());
		   		   bizShareDao.insert(bizShare);
		   		}
				return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(bizQrcode));
			}else{
				
				//查询到就返回
				return new AjaxResult(AjaxResult.STATUS_SUCCESS,list);
			}
		} catch (Exception e) {
			LogUtil.error("生成二维码错误:{}", e, "");
		}
   	
		return new AjaxResult(AjaxResult.STATUS_FAIL,null);
	}
   	/**
	 * 生成二维码
	 */   
   	@RequestMapping(value =  "/getwxacode1/{actId}/{formId}")
	public @ResponseBody AjaxResult getwxacode1(@PathVariable("actId") String actId,@PathVariable("formId") String formId) {
   		BizUser loginUser = redisUserLoginUtils.getLoginUser();
   		String url;
		try {
			BizShare bizShare=new BizShare();
			BizQrcode bizQrcode=new BizQrcode();
			bizQrcode.setActId(actId);
			bizQrcode.setUserId(loginUser.getOpenId());
			List<BizQrcode> list=
			bizQrcodeDao.selectByModel(bizQrcode);
			if(CollectionUtils.isEmpty(list)){
				//如果未查询到就先插入数据再更新数据
				bizQrcode.setCreateBy(loginUser.getOpenId());
				bizQrcode.setUpdateBy(loginUser.getOpenId());
				bizQrcodeDao.insert(bizQrcode);
				url = WxacodeUtil.getWxacode(bizQrcode.getCodeId()+"", "pages/active/active", actId+loginUser.getUserId());
				bizQrcode.setCodeUrl(url);
				BizHelpActivity helpActivity=helpActivityDao.selectByActId(actId);
				String posterImg=helpActivity.getHacPosterImg();
				// 图片保存目录路径
				String baseSavePath = PropertiesUtil.getString(AppConstance.FILES_TORAGE_PATH);
				// 图片保存目录URL
				String baseSaveUrl = PropertiesUtil.getString(AppConstance.NGINX_URL);
				posterImg=posterImg.replace(baseSaveUrl, baseSavePath);
				String smallUrl=url.replace(baseSaveUrl, baseSavePath);
				BufferedImage big = ImageIO.read(new File(posterImg));
		        BufferedImage small = ImageIO.read(new File(smallUrl));
		        Graphics2D g = big.createGraphics();
		        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));
		        g.drawImage(small, 400, 335, 150, 150, null);
		        g.dispose();
		        String fileName=UUIDUtil.getRandomID()+".png";
		        	
		        ImageIO.write(big, "png", new File(baseSavePath+fileName));
		        bizQrcode.setCodeRemark(baseSaveUrl+fileName);
				bizQrcodeDao.updateByModel(bizQrcode);
		   		
		   		bizShare.setProId(actId);
		   		bizShare.setUserId(loginUser.getOpenId());
		   		List<BizShare> sharelist=bizShareDao.selectByModel(bizShare);
		   		if(CollectionUtils.isEmpty(sharelist)){
		   			bizShare.setCreateBy(loginUser.getOpenId());
		   			bizShare.setUpdateBy(loginUser.getOpenId());
		   			bizShare.setShaStatus(AppConstance.SHARE_STATUS_YFX);
		   			bizShare.setShaRemark(formId);
		   			bizShare.setShaId(UUIDUtil.getRandomID());
		   		   bizShareDao.insert(bizShare);
		   		}
				return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(bizQrcode));
			}else{
				//更新formId
				bizShare=bizShareDao.selectShareInfo(loginUser.getOpenId(), actId);
				bizShare.setShaRemark(formId);
				bizShareDao.updateByModel(bizShare);
				//查询到就返回
				return new AjaxResult(AjaxResult.STATUS_SUCCESS,list);
			}
		} catch (Exception e) {
			LogUtil.error("生成二维码错误:{}", e, "");
		}
   	
		return new AjaxResult(AjaxResult.STATUS_FAIL,null);
	}
   	/**
	 * 根据二维码ID查询
	 */   
   	@RequestMapping(value =  "/getCodeInfo/{codeId}")
	public @ResponseBody AjaxResult getwxacode(@PathVariable("codeId") Long codeId) {
   		BizQrcode bizQrcode=bizQrcodeDao.selectById(codeId);
   		return new AjaxResult(AjaxResult.STATUS_SUCCESS,Arrays.asList(bizQrcode));
   	}
	
}